package com.yim.counter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 代码行数统计
 * @author chenzhiyan
 * @version v1.0
 */
public class LineCounter {
List<File> list = new ArrayList<File>();
	
	int lineNumber =0;
	
	FileReader fr = null;
	BufferedReader br = null;
	
	public void counter(String projectName){
		//取得项目的路径
		String path = LineCounter.class.getResource("/").getPath();
		path = path.substring(0, path.length()-24)+projectName+"/src";
		System.out.println("要统计的代码行数的路径:"+path);
		File file = new File(path);
		File[] files = null;
		files = file.listFiles();
		
		addFile(files);
		isDirectory(files);
		readLinePerFile();
	}

	public void readLinePerFile() {
		try {
			for (File s : list) {
				int yuan = lineNumber;
				if (s.isDirectory()) {
					continue;
				}
				fr = new FileReader(s);
				br = new BufferedReader(fr);
				String i = "";
				while ((i=br.readLine())!=null) {
					if(isBlankLine(i)){
						lineNumber ++;
					}
				}
				System.out.print(s.getName());
				System.out.println("\t\t有"+(lineNumber-yuan));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (br!=null) {
				try {
					br.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			if (fr!=null) {
				try {
					fr.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}

	public boolean isBlankLine(String i) {
		if (i.trim().length()==0) {
			return false;
		}else {
			return true;
		}
		
	}

	public void isDirectory(File[] files) {
		for (File s:files) {
			if (s.isDirectory()) {
				File[] file = s.listFiles();
				addFile(file);
				isDirectory(file);
				continue;
			}
			
		}
	}

	public void addFile(File[] files) {
		for (int i = 0; i < files.length; i++) {
			list.add(files[i]);
		}
	}
}
